<template>
  <el-drawer
    v-model="dialogVisible"
    :title="dialogStatus==='create'?'新增': (dialogStatus === 'view' ? '查看' : '编辑')"
    width="600px"
    @close="reset"
  >
    <el-form 
      ref="articleFormRef"
      :model="tableItem" 
      :rules="rules"
      label-width="180"
      label-position="top"
      :disabled="!isDisabled"
    >
      <el-form-item label="商家名称" prop="tenantName">
        <el-input v-model="tableItem.tenantName" placeholder="请输入商家名称" />
      </el-form-item>

      <el-form-item label="联系人" prop="contactPerson">
        <el-input v-model="tableItem.contactPerson" placeholder="请输入联系人" />
      </el-form-item>

      <el-form-item label="联系电话" prop="customerPhone">
        <el-input v-model="tableItem.customerPhone" placeholder="请输入联系电话" />
      </el-form-item>
      
      <el-form-item label="商户地址" prop="tenantAddress">
        <el-input v-model="tableItem.tenantAddress" placeholder="请输入商户地址" />
      </el-form-item>

      <el-form-item label="所属行业" prop="industry">
        <el-select v-model="tableItem.industry" placeholder="请选择所属行业">
          <el-option v-for="item in industryList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="经营场所" prop="businessScenario">
        <el-checkbox-group v-model="tableItem.businessScenario">
          <el-checkbox value="线下场景" name="type">线下场景</el-checkbox>
          <el-checkbox value="公众号" name="type">公众号</el-checkbox>
          <el-checkbox value="小程序" name="type">小程序</el-checkbox>
          <el-checkbox value="APP" name="type">APP</el-checkbox>
          <el-checkbox value="PC网站" name="type">PC网站</el-checkbox>
          <el-checkbox value="企业微信" name="type">企业微信</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="tableItem.remark" placeholder="请输入备注" />
      </el-form-item>

      <el-form-item label="营业执照照片" prop="businessLicensePic" class="add-no">
        <el-upload 
          :file-list="tableItem.uploadPhotoDtoList.filter((item: any)=>item.photoType == 'yyzz')"
          accept=".jpg,.jpeg,.png,.gif" 
          list-type="picture-card"
          :show-file-list="true"
          :action="`/base-api/file/upload`" 
          :headers="headers" 
          :on-success="(data: any, uploadFile: any)=>handleUploadSuccess(data, uploadFile, 'photo', 'yyzz')"
          :on-error="handleUploadError"
          :on-remove="removeItem"
          name="files"
          style="display: inline-block; margin: 0 10px 0 0; vertical-align: middle;"
          auto-upload
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">
              推荐加上水印，仅供微信支付平台申请商户使用，他用无效
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="法人代表人证件照片" prop="legalPersonFrontPic" class="add-no">
        <el-upload 
          :file-list="tableItem.uploadPhotoDtoList.filter((item: any)=>item.photoType == 'frzm')"
          accept=".jpg,.jpeg,.png,.gif" 
          list-type="picture-card"
          :show-file-list="true"
          :action="`/base-api/file/upload`" 
          :headers="headers" 
          :on-success="(data: any, uploadFile: any)=>handleUploadSuccess(data, uploadFile, 'photo', 'frzm')"
          :on-error="handleUploadError"
          :on-remove="removeItem"
          name="files"
          style="display: inline-block; margin: 0 10px 0 0; vertical-align: middle;"
          auto-upload
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">
              推荐加上水印，仅供微信支付平台申请商户使用，他用无效
            </div>
          </template>
        </el-upload>
        <el-upload 
          :file-list="tableItem.uploadPhotoDtoList.filter((item: any)=>item.photoType == 'frfm')"
          accept=".jpg,.jpeg,.png,.gif" 
          list-type="picture-card"
          :show-file-list="true"
          :action="`/base-api/file/upload`" 
          :headers="headers" 
          :on-success="(data: any, uploadFile: any)=>handleUploadSuccess(data, uploadFile, 'photo', 'frfm')"
          :on-error="handleUploadError"
          :on-remove="removeItem"
          name="files"
          style="display: inline-block; margin: 0 10px 0 0; vertical-align: middle;"
          auto-upload
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">
              推荐加上水印，仅供微信支付平台申请商户使用，他用无效
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="银行账号" prop="bankCardNum">
        <el-input v-model="tableItem.bankCardNum" placeholder="请输入银行账号" />
      </el-form-item>

      <el-form-item label="开户银行" prop="bankOpen">
        <el-input v-model="tableItem.bankOpen" placeholder="请输入开户银行" />
      </el-form-item>
      
<!--       <el-form-item label="超级管理员身份证" prop="superAdminFrontPic" class="add-no">
        <el-upload 
          :file-list="tableItem.uploadPhotoDtoList.filter((item: any)=>item.photoType == 'glzm')"
          accept=".jpg,.jpeg,.png,.gif" 
          list-type="picture-card"
          :show-file-list="true"
          :action="`/base-api/file/upload`" 
          :headers="headers" 
          :on-success="(data: any, uploadFile: any)=>handleUploadSuccess(data, uploadFile, 'photo', 'glzm')"
          :on-error="handleUploadError"
          :on-remove="removeItem"
          name="files"
          style="display: inline-block; margin: 0 10px 0 0; vertical-align: middle;"
          auto-upload
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">
              推荐加上水印，仅供微信支付平台申请商户使用，他用无效
            </div>
          </template>
        </el-upload>
        <el-upload 
          :file-list="tableItem.uploadPhotoDtoList.filter((item: any)=>item.photoType == 'glfm')"
          accept=".jpg,.jpeg,.png,.gif" 
          list-type="picture-card"
          :show-file-list="true"
          :action="`/base-api/file/upload`" 
          :headers="headers" 
          :on-success="(data: any, uploadFile: any)=>handleUploadSuccess(data, uploadFile, 'photo', 'glfm')"
          :on-error="handleUploadError"
          :on-remove="removeItem"
          name="files"
          style="display: inline-block; margin: 0 10px 0 0; vertical-align: middle;"
          auto-upload
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">
              推荐加上水印，仅供微信支付平台申请商户使用，他用无效
            </div>
          </template>
        </el-upload>
      </el-form-item>
 -->
      <el-form-item label="业务办理授权函" prop="authLetter" class="add-no">
        <el-upload 
          :file-list="tableItem.uploadPhotoDtoList.filter((item: any)=>item.photoType == 'ywhs')"
          accept=".jpg,.jpeg,.png,.gif" 
          list-type="picture-card"
          :show-file-list="true"
          :action="`/base-api/file/upload`" 
          :headers="headers" 
          :on-success="(data: any, uploadFile: any)=>handleUploadSuccess(data, uploadFile, 'photo', 'ywhs')"
          :on-error="handleUploadError"
          :on-remove="removeItem"
          name="files"
          style="display: inline-block; margin: 0 10px 0 0; vertical-align: middle;"
          auto-upload
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">
              请打印并上传加盖公章的业务办理授权扫描件
            </div>
          </template>
        </el-upload>
      </el-form-item>
<!-- 
      <el-form-item label="超级管理员手机号码" prop="superAdminPhone">
        <el-input v-model="tableItem.superAdminPhone" placeholder="请输入超级管理员手机号码" />
      </el-form-item>

      <el-form-item label="超级管理员邮箱" prop="superAdminEmail">
        <el-input v-model="tableItem.superAdminEmail" placeholder="请输入超级管理员邮箱" />
      </el-form-item>
 -->
    </el-form>
    <template #footer v-if="isDisabled">
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus==='create'?createData():updateData()"
        >确 定</el-button>
      </span>
    </template>
  </el-drawer>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { addMerchant, editMerchant } from '@/api/settle'
import { validate } from '@/utils/validate'
import { getToken } from '@/utils/user';
import { getDist } from '@/api/collect'

const isDisabled = ref(true)
const industryList = ref<any>([])
const tableItem = reactive({
  id: undefined,
  projectId: undefined,
  tenantName: '',
  contactPerson: '',
  customerPhone: '',
  tenantAddress: '',
  industry: '',
  businessScenario: [],
  businessLicensePic: '',
  legalPersonFrontPic: '',
  legalPersonBackPic: '',
  bankCardNum: '',
  bankOpen: '',
  superAdminFrontPic: '',
  superAdminBackPic: '',
  authLetter: '',
  superAdminPhone: '',
  superAdminEmail: '',
  uploadPhotoDtoList: [],
  remark:''
})

const rules = reactive({
  // projectId: [{ required: true, message: '请选择一个项目', trigger: 'change' }],
  // businessLicensePic: [{ required: true, message: '请上传照片', trigger: 'change' }],
  // legalPersonFrontPic: [{ required: true, message: '请上传照片', trigger: 'change' }],
  // legalPersonBackPic: [{ required: true, message: '请上传照片', trigger: 'change' }],
  tenantName: [{ required: true, message: '请输入商户名称', trigger: 'blur' }],
  contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  customerPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  tenantAddress: [{ required: true, message: '请输入商户地址', trigger: 'blur' }],
  // industry: [{ required: true, message: '请输入所属行业', trigger: 'blur' }],
  // businessScenario: [{ required: true, message: '请输入经营场所', trigger: 'blur' }],
  // bankCardNum: [{ required: true, message: '请输入银行账号', trigger: 'blur' }],
  // bankOpen: [{ required: true, message: '请输入开户银行', trigger: 'blur' }],
  // superAdminPhone: [{ required: true, message: '请输入超级管理员手机号码', trigger: 'blur' }],
  // superAdminEmail: [{ required: true, message: '请输入超级管理员邮箱', trigger: 'blur' }],
})

const dialogVisible = ref(false)
const dialogStatus = ref('create')

// 页面加载时获取所属行业列表
onMounted(() => {
  getDistData()
})

const reset = () => {
  if (!articleFormRef) return
  articleFormRef.value.resetFields()
  // isDisabled.value = false
  tableItem.uploadPhotoDtoList = []
}

const articleFormRef = ref<any>(null)

const emit = defineEmits(['listChange'])

const token = getToken();

const headers = { Authorization: `${token}` }

const getDistData = () => {
  getDist('DC00012')
  .then((res: any)=>{
    industryList.value = res.data
  })
}

const handleUploadSuccess = (data: any, uploadFile: any, type: string, photoType: string) => {
  if (data.success == true) {
    // console.log('data', data)
    const params = {
      appendixType: type,
      photoType: photoType || '',
      name: '',
      url: '',
    }
    // 图片预览数据
    params.url = data.data[0]
    params.name = uploadFile.name
    tableItem.uploadPhotoDtoList.push(params)
    // 提交用数据
    if (photoType == 'yyzz') {
      tableItem.businessLicensePic = data.data[0]
    } else if (photoType == 'frzm') {
      tableItem.legalPersonFrontPic = data.data[0]
    } else if (photoType == 'frfm') {
      tableItem.legalPersonBackPic = data.data[0]
    } else if (photoType == 'glzm') {
      tableItem.superAdminFrontPic = data.data[0]
    } else if (photoType == 'glfm') {
      tableItem.superAdminBackPic = data.data[0]
    } else {
      // photoType == 'ywhs'
      tableItem.authLetter = data.data[0]
    }
    
    // console.log('formItem.uploadPhotoDtoList', formItem.uploadPhotoDtoList)
    ElMessage.success(data.msg)
  } else {
    ElMessage.error(data.msg);
  }
}

const removeItem = (i: any) => {
  // console.log('remove-item', i)
  const removeIndex = tableItem.uploadPhotoDtoList.findIndex((item: any) => i.url == item.url)
  tableItem.uploadPhotoDtoList.splice(removeIndex, 1)
  // console.log('formItem.uploadPhotoDtoList', formItem.uploadPhotoDtoList)
}

const handleUploadError = (err: any) => {
  const message = JSON.parse(err.toString().replace('UploadAjaxError: ', '')).msg
  ElMessage.error(message)
}

const createData = async () => {
  const valid = await validate(articleFormRef)
  if (valid) {
    addMerchant({...tableItem,businessScenario:tableItem.businessScenario.join(',')})
    .then(() => {
      // TODO use res data
      emit('listChange')
      dialogVisible.value = false
      ElMessage.success('创建成功！')
    })
    .catch((err) => {
      ElMessage.error(err.msg)
    })
  }
}

const updateData = async () => {
  const valid = await validate(articleFormRef)
  if (valid) {
    editMerchant({...tableItem,businessScenario:tableItem.businessScenario.join(',')})
    .then(() => {
      // TODO use res data
      emit('listChange')
      dialogVisible.value = false
      ElMessage.success('更新成功！')
    })
    .catch((err) => {
      ElMessage.error(err.msg)
    })
  }
}

defineExpose({ dialogVisible, tableItem, isDisabled, dialogStatus, reset })

</script>
<style lang="scss" scoped>
.add-no {
  :deep(.el-upload-list) {
    .el-upload-list__item + .el-upload {
      display: none;
    }
  }
}
</style>
